package com.vn.gofriends.activity;

import java.io.ByteArrayOutputStream;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseUser;
import com.parse.SignUpCallback;
import com.vn.gofriends.R;

public class SignupActivity extends Activity {
	public static String TAG = "SigupActivity";
	private String usernametxt;
	private String passwordtxt;
	private String emailtxt;
	private String phonetxt;
	private String locationtxt;
	private EditText txtUserName;
	private EditText txtPassword;
	private EditText txtEmail;
	private EditText txtPhone;
	private EditText txtLocation;
	private Button btnSign;
	private Button btnUploadImage;
	private ParseFile file;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.signup);
		txtUserName = (EditText) findViewById(R.id.username_sign);
		txtPassword = (EditText) findViewById(R.id.pass_Sign);
		txtEmail = (EditText) findViewById(R.id.mail_sign);
		txtPhone = (EditText) findViewById(R.id.phoneSign);
		txtLocation = (EditText) findViewById(R.id.locationSign);
		btnSign = (Button) findViewById(R.id.sign);
		btnUploadImage = (Button) findViewById(R.id.btnUploadLogo);
		
		btnUploadImage.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				   Intent intent = new Intent();
	                intent.setType("image/*");
	                intent.setAction(Intent.ACTION_GET_CONTENT);
	                startActivityForResult(
	                        Intent.createChooser(intent, "Select Picture"),
	                        1000);
			}
		});
		
		btnSign.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				// Retrieve the text entered from the EditText

				usernametxt = txtUserName.getText().toString().trim();
				passwordtxt = txtPassword.getText().toString().trim();
				emailtxt = txtEmail.getText().toString().trim();
				phonetxt = txtPhone.getText().toString().trim();
				locationtxt = txtLocation.getText().toString().trim();
				boolean validationError = false;
				StringBuilder validationErrorMessage = new StringBuilder(
						getResources().getString(R.string.error_intro));
				if (isEmpty(txtUserName)) {
					validationError = true;
					validationErrorMessage.append(getResources().getString(
							R.string.error_blank_username));
				}
				if (isEmpty(txtPassword)) {
					if (validationError) {
						validationErrorMessage.append(getResources().getString(
								R.string.error_join));
					}
					validationError = true;
					validationErrorMessage.append(getResources().getString(
							R.string.error_blank_password));
				}
				validationErrorMessage.append(getResources().getString(
						R.string.error_end));

				// If there is a validation error, display the error
				if (validationError) {
					Toast.makeText(getApplicationContext(),
							validationErrorMessage.toString(),
							Toast.LENGTH_LONG).show();
					return;
				}
				// Set up a progress dialog
				final ProgressDialog dlg = new ProgressDialog(
						SignupActivity.this);
				dlg.setTitle("Please wait.");
				dlg.setMessage("Sign up.  Please wait...");
				dlg.show();
				// Force user to fill up the form
				if (usernametxt.equals("") && passwordtxt.equals("")) {
					Toast.makeText(getApplicationContext(),
							"Please complete the sign up form",
							Toast.LENGTH_LONG).show();

				} else {
					// Save new user data into Parse.com Data Storage
					ParseUser user = ParseUser.getCurrentUser();
					if (user != null) {
						user = new ParseUser();
						user.setUsername(usernametxt);
						user.setPassword(passwordtxt);
						user.setEmail(emailtxt);
						user.put("phone", Integer.parseInt(phonetxt));
						user.put("Location", locationtxt);
//						Bitmap bitmap = BitmapFactory.decodeFile(selectedImagePath);
//						
//						// Convert it to byte
//						ByteArrayOutputStream stream = new ByteArrayOutputStream();
//						// Compress image to lower quality scale 1 - 100
//						bitmap.compress(Bitmap.CompressFormat.PNG, 48, stream);
//						byte[] image = stream.toByteArray();
//		 
//						// Create the ParseFile
//						file = new ParseFile("logo", image);
//						// Upload the image into Parse Cloud
//						file.saveInBackground();
//						// Create a column named "ImageFile" and insert the image
//						user.put("avartar", file);
						// user.put(key, value);
						user.signUpInBackground(new SignUpCallback() {
							public void done(ParseException e) {
								dlg.cancel();
								if (e == null) {
									// Show a simple Toast message upon
									// successful
									// registration
									Toast.makeText(
											getApplicationContext(),
											"Successfully Signed up, please log in.",
											Toast.LENGTH_LONG).show();
									startActivity(new Intent(
											SignupActivity.this,
											MainActivity.class));
								} else {
									Toast.makeText(getApplicationContext(),
											"Sign up Error: " + e.getMessage(),
											Toast.LENGTH_LONG).show();
									Log.d(TAG, e.getMessage());
								}
							}
						});
					} else {
						dlg.cancel();
						Log.d(TAG, "user!= null");
					}
				}

			}
		});
	}

	private boolean isEmpty(EditText etText) {
		if (etText.getText().toString().trim().length() > 0) {
			return false;
		} else {
			return true;
		}
	}

	private String selectedImagePath;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			if (requestCode == 1000) {
				Uri selectedImageUri = data.getData();
				selectedImagePath = getPath(selectedImageUri);
				Log.d("Vien", "Image Path : " + selectedImagePath);
				
			}
		}
	}

	public String getPath(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}
}
